﻿using System;

using Pibby.Core.Feeds;

namespace Pibby.Core
{
	public class EpisodeCollectionBuilder
	{
		public EpisodeCollectionBuilder()
		{
			this.Episodes = new EpisodeCollection();
		}

		public EpisodeCollection Episodes
		{
			get;
			private set;
		}

		public int NewEpisodes
		{
			get;
			private set;
		}

		public void Build(Feed feed, Podcast podcast, DateTime lastUpdated)
		{
			this.Episodes.AddRange(this.Load(feed, podcast, lastUpdated));
		}

		private EpisodeCollection Load(Feed feed, Podcast podcast, DateTime lastUpdated)
		{
			var episodes = new EpisodeCollection();
			var classifier = new EpisodeClassifier(lastUpdated);

			this.NewEpisodes = 0;

			foreach (var rssItem in feed.Items)
			{
				if (rssItem.Enclosure != null && rssItem.Enclosure.MimeType == EnclosureMimeType.Audio)
				{
					var episode = new Episode()
					{
						Id = rssItem.Id,
						Name = rssItem.Title,
						Feed = rssItem.Enclosure.Url,
						SubscriptionID = podcast.PrimaryKey.Value,
						PodcastName = podcast.SafeName,
						PublicationDate = rssItem.PublicationDate,
						Duration = rssItem.Duration,
						FileSize = rssItem.Enclosure.Length,
						Description = rssItem.Description
					};

					classifier.Classify(episode);

					episodes.Add(episode);

					if (lastUpdated != DateTime.MinValue && episode.PublicationDate > lastUpdated)
					{
						// assuming when last updated would include 
						// items with the same date
						++this.NewEpisodes;
					}
				}
			}

			if (this.NewEpisodes > 0)
			{
				// some new episodes have been published - increase whuffie...
				podcast.Whuffie.Esteem(WhuffieRules.EsteemForNewEpisode * this.NewEpisodes);
			}

			return episodes;
		}
	}
}
